﻿using Microsoft.Extensions.Configuration;
using System.Collections.Concurrent;

namespace SDK.Core
{
    public sealed class ConfigHelper
    {
        private static readonly ConcurrentDictionary<string, IConfigurationRoot> _configurationCache;

        static ConfigHelper()
        {
            _configurationCache = new ConcurrentDictionary<string, IConfigurationRoot>();
        }

        public static T GetValue<T>(string key) where T : class
        {
            IConfigurationRoot configurationRoot = GetFromEnv();

            return configurationRoot[key] as T;
        }

        private static IConfigurationRoot GetFromEnv()
        {
#if DEV || DEBUG||WDEBUG
            return Get("Development");
#elif RELEASE
            return Get("Production");
#endif
        }

        private static IConfigurationRoot Get(string environmentName = null, bool addUserSecrets = false)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;

            var cacheKey = path + "#" + environmentName + "#" + addUserSecrets;
            return _configurationCache.GetOrAdd(
                cacheKey,
                _ => BuildConfiguration(path, environmentName, addUserSecrets)
            );
        }

        private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(path)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            if (!string.IsNullOrEmpty(environmentName))
            {
                builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true);
            }

            builder = builder.AddEnvironmentVariables();

            if (addUserSecrets)
            {
                builder.AddUserSecrets(typeof(ConfigHelper).Assembly);
            }

            return builder.Build();
        }
    }
}
